<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    @register="registerDrawer"
    @ok="handleSubmit"
    okText="保存"
    width="80%"
    :okAuth="'wh:tl:whTmTl:edit'"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <div style="font-size: 20px; padding: 30px">
      总退料申请数：
      <span style="font-size: 26px; color: red; margin-right: 80px">{{ record.barSumQty }}条</span>
    </div>
    <BasicForm @register="registerForm">
      <template #TlDataChildList>
        <BasicTable @register="registerTlDataChildTable" @row-click="handleTestDataChildRowClick" />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsOrderM8OperCheckForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { batchSave } from '/@/api/wh/tl/whTmTl';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { officeTreeData } from '/@/api/sys/office';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('order.m8OperCheck');
  const { showMessage } = useMessage();
  const record = ref<any>({
    picSumQty: '',
    checkSumQty: '',
    checkList: [],
  });
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: '批量退料申请',
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('申请人'),
      field: 'user.userCode',
      fieldLabel: 'user.userName',
      component: 'TreeSelect',
      required: true,
      componentProps: {
        api: officeTreeData,
        params: { isLoadUser: true, userIdPrefix: '', isAll: true, isShowCode: true },
        immediate: true,
        canSelectParent: false,
        maxlength: 64,
      },
    },
    {
      label: '',
      field: 'childList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'TlDataChildList',
    },
  ];

  const [registerTlDataChildTable, tlDataChildTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleTLDataChildDelete.bind(this, record),
          },
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    canResize: true,
    resizeHeightOffset: 80,
  });

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    record.value = data;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setTlDataChildTableData(data);
    setDrawerProps({ loading: false });
  });

  function handleTLDataChildDelete(record: Recordable) {
    tlDataChildTable.deleteTableDataRecord(record);
  }

  async function setTlDataChildTableData(_res: Recordable) {
    tlDataChildTable.setColumns([
      {
        title: t('物料编码'),
        dataIndex: 'basInv.cinvcode',
        width: 130,
        align: 'left',
      },
      {
        title: t('物料代码'),
        dataIndex: 'basInv.cinvaddcode',
        width: 130,
        align: 'left',
      },
      {
        title: t('物料名称'),
        dataIndex: 'basInv.cinvname',
        width: 80,
        align: 'left',
      },
      {
        title: t('规格型号'),
        dataIndex: 'basInv.cinvstd',
        width: 80,
        align: 'left',
      },
      {
        title: t('仓库'),
        dataIndex: 'cwhcode',
        width: 130,
        align: 'left',
      },
      {
        title: t('批次'),
        dataIndex: 'cbatch',
        width: 130,
        align: 'left',
      },
      {
        title: t('退料数量'),
        dataIndex: 'iqty',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
          rules: [
            {
              pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/,
              message: t('请输入一个数值'),
            },
          ],
        },
        editRule: true,
      },
      {
        title: t('来源单号'),
        dataIndex: 'xppno',
        width: 130,
        align: 'left',
      },
    ]);
    let arr: any = [];
    record.value.list.forEach((item, index) => {
      arr = [
        ...arr,
        {
          basInv: item.basInv,
          cwhcode: item.cwhcode,
          cbatch: item.cbatch,
          iqty: item.iqty,
          xppno: item.xppno,
          id: index + 1,
        },
      ];
    });
    tlDataChildTable.setTableData(arr || []);
  }

  function handleTestDataChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  async function getwhTmTlList() {
    let whTmLlRdsListValid = true;
    let whTmLlRdsList: Recordable[] = [];
    for (const record of tlDataChildTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        whTmLlRdsListValid = false;
      }
      whTmLlRdsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of tlDataChildTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      whTmLlRdsList.push({
        ...record,
        status: '1',
      });
    }
    if (!whTmLlRdsListValid) {
      throw { errorFields: [{ name: ['whTmLlRdsList'] }] };
    }
    return whTmLlRdsList;
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });

      let flag = true;
      let arr = await getwhTmTlList();
      if (arr.length < 1) {
        showMessage('无保存数据，请检查!');
        return;
      }
      const params: any = {
        selIds: JSON.stringify(arr),
        createBy: data.user.userCode,
      };
      if (flag) {
        const res = await batchSave(params);
        showMessage(res.message);
        setTimeout(closeDrawer);
        emit('success', data);
      } else {
        showMessage(t('存货不能为空！'));
      }
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
